package me.linx.demo

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.util.Base64
import android.webkit.CookieManager
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_webview.*
import java.io.IOException
import java.io.InputStream

class WebViewActivity : AppCompatActivity() {

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webview)
        val webSettings = webview.settings
        setCookie()
        webSettings.javaScriptEnabled = true
        webSettings.useWideViewPort = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
        webSettings.domStorageEnabled = true
        webview.addJavascriptInterface(this, "yt")
        webview.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                injectScriptFile(webview, "js/script.js")
            }
        }
        webview.loadUrl("http://open.ximalaya.com/site/index/288/2e9977cfe497b2e06b65799e94f58b13")
    }

    private fun injectScriptFile(view: WebView, scriptFile: String) {
        val input: InputStream
        try {
            input = assets.open(scriptFile)
            val buffer = ByteArray(input.available())
            input.read(buffer)
            input.close()

            // String-ify the script byte-array using BASE64 encoding !!!
            val encoded: String = Base64.encodeToString(buffer, Base64.NO_WRAP)
            view.loadUrl(
                "javascript:(function() {" +
                        "var parent = document.getElementsByTagName('head').item(0);" +
                        "var script = document.createElement('script');" +
                        "script.type = 'text/javascript';" +  // Tell the browser to BASE64-decode the string into your script !!!
                        "script.innerHTML = window.atob('" + encoded + "');" +
                        "parent.appendChild(script)" +
                        "})()"
            )
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    @JavascriptInterface
    fun refreshToken() {
        println("refresh token invoke")
        val testToken = "test_token"
        webview.post {
            webview.loadUrl("javascript:refreshYtToken('$testToken')")
        }
    }

    @JavascriptInterface
    fun receiveToken(token: String) {
        println("refresh token receive $token")
    }

    /**
     * 给WebView同步Cookie
     */
    private fun setCookie(){
//        if("unlogin"== Account.getXmAccountAccessToken()){
//            return
//        }
        var url = ".ximalaya.com"
        val cookieManager = CookieManager.getInstance()
        cookieManager.setAcceptCookie(true)
//        cookieManager.setCookie(url, "assess_token="+Account.getXmAccountAccessToken())
        cookieManager.setCookie(url, "assess_token="+"6f0a5a2afc09390045ad2d9dc143999b")
        var domain = "Domain=$url"
        var path = "Path=/"
        cookieManager.setCookie(url, domain)
        cookieManager.setCookie(url, path)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush()
        }
    }


}